package com.chinaums.fsp.sdk.request;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import org.xiajinsuo.avro.specific.SpecificRecordBase;

import com.alibaba.fastjson.JSON;
import com.chinaums.fsp.exception.NotFoundException;
import com.chinaums.fsp.sdk.base.RequestData;
import com.chinaums.fsp.sdk.base.ResponseDataWrapper;
import com.chinaums.fsp.sdk.base.SignType;
import com.chinaums.fsp.sdk.ca.CaGenerator;

import junit.framework.TestCase;

public class BaseRequest extends TestCase {
	protected Certificate	serverCertificate;
	protected KeyStore		clientKeyStore;
	protected final String	KEYSTORE_PASSWORD	= "123456";
	protected final String	PRIVATEKEY_PASSWORD	= "123456";
	protected final String	appId				= "80100000000202000000000";//"462b01f0213148f5b1d297ec7a488cdf";
//	protected final String	appId				= "80100000000191600000001";//"462b01f0213148f5b1d297ec7a488cdf";
//	protected final String	appId				= "80100000000042100000000";//"462b01f0213148f5b1d297ec7a488cdf";生产
//	protected final String	appId				= "80100000000162700000001";//"462b01f0213148f5b1d297ec7a488cdf";
//	protected final String	appId				= "80100000000138700000001";//"462b01f0213148f5b1d297ec7a488cdf";
	// 机构注册
//	protected final String	url					= "http://218.5.69.218:9088/pgt-api/api/v1/service.json";
//	protected final String	url					= "http://218.5.69.218:9088/pgt-api/api/v1/register.json";
	// 机构注册
//	protected final String	url					= "http://127.0.0.1:8083/pgt-api/api/v1/service.json";
//	protected final String	url					= "http://172.16.208.90:30011/pgt-api/api/v1/service.json";
//	protected final String	url					= "http://172.16.208.82:30011/pgt-api/api/v1/service.json";
//	protected final String	url					= "https://piaoju.tjfadc.com:8088/pgt-api/api/v1/discountService.json";
//	protected final String	url					= "http://127.0.0.1:8083/pgt-api/api/v1/discountService.json";
//	protected final String	url					= "http://218.5.69.218:9088/pgt-api/api/v1/discountService.json";
//	protected final String	url					= "http://127.0.0.1:8083/pgt-api/api/v1/register.json";
//	protected final String	url					= "http://172.16.208.82:30011/pgt-api/api/v1/draftUpload.json";
	protected final String	url					= "http://172.16.208.82:30011/pgt-api/api/v1/service.json";
//	protected final String	url					= "http://192.168.31.217:8777/pgt-api/api/v1/register.json";
//	protected final String	url					= "http://127.0.0.1:8093/api/v1/service.json";
//	protected final String	url					= "http://172.16.208.90:30011/pgt-api/api/v1/register.json";
	// 回调地址
	protected final String callbackUrl = " http://127.0.0.1:8083/pgt-api/api/v1/callback.json"; // http://127.0.0.1:8761/callback
	private final String version = "1.0.0";
	protected final String countWalletAccountNo = "0100100010005";//"0100100010005";
//	protected final String CMBC_WALLET_ACCOUNT_NO = "695603264000105";
	protected PgtRequestFactory FACTORY;
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		this.serverCertificate = CaGenerator
				.getCertificate(this.getInputStream("/certs/fsp_server.cer"));
		this.clientKeyStore = CaGenerator.getKeyStore(
				CaGenerator.KEYSTORE_PKCS12,
				this.getInputStream("/certs/fsp_client.pfx"),
				KEYSTORE_PASSWORD.toCharArray());
		
		FACTORY = new PgtRequestFactory(appId, callbackUrl, version, url, CaGenerator.getPrivateKey(clientKeyStore, PRIVATEKEY_PASSWORD), this.serverCertificate.getPublicKey());
	}

	protected static InputStream getInputStream(String path) throws Exception {
		InputStream in = BaseRequest.class.getResourceAsStream(path);
		if (null == in) {
			throw new NotFoundException("未找到" + path + "证书");
		}
		return in;
	}

	protected RequestData.Builder createRequestDataBuilder() {
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		String nanoTime = System.nanoTime() + "";
		RequestData.Builder builder = RequestData.newBuilder();
		builder.setAppId(appId).setCallbackUrl("")
				.setClientTransId(
						time + nanoTime.substring(nanoTime.length() - 6))
				.setSignType(SignType.RSA)
				.setTransTimestamp(System.currentTimeMillis())
				.setVersion("1.0.0");
		return builder;
	}

//	// 请求测试
//	public void testRequest() throws Exception {
//		long start = System.currentTimeMillis();
//		RequestData.Builder builder = this.createRequestDataBuilder();
//		builder.setTransType("0201");
//		PragencyRequest data = PragencyRequest.newBuilder()
//				 							// 现金账户	
//											// .setWalletAccountNo("02001300006")
//											// 民生电子账户
//											.setWalletAccountNo("695603264000105")
//											.setAmount(1L)
//											// 发起者信息
//											.setSendAccName("张三")
//											.setSendAccNo("53332414141")
//											.setSendBankcode("")
//											.setSendBankname("")
//											.setSendBankSettleno("324231421412")
//											.setSendIdcard("33532532523453252")
//											.setSendIdType(IDType.ID_CARD.ordinal())
//											
//											// 收款方
//											.setReceiveAccname("李四2")
//											.setReceiveAccno("6210181930000000022")
//											.setReceiveBankcode("ICBC")
//											.setReceiveBankname("中国工商银行")
//											.setReceiveBankSettleno("")
//											.setReceiveIdcard("32453252354")
//											.setReceiveIdType(IDType.ID_CARD.ordinal())
//											.setReceiveMobile("13855123000")
//											
//											.setBusinessType("06")
//											.setDescription("备注")
//											.build();
//		ResponseDataWrapper rdw = SDKUtil.post(url, builder, data,
//				PragencyResponse.class, this.serverCertificate.getPublicKey(),
//				CaGenerator.getPrivateKey(clientKeyStore, PRIVATEKEY_PASSWORD));
//		System.out.println(rdw);
//		if (null != rdw.getResponseData()) {
//			System.out.println(rdw.getResponseData());
//		}
//		System.out.println("takes " + (System.currentTimeMillis() - start));
//	}
//	
//	// 请求测试
//	public void testCreditQueryRequest() throws Exception {
//			long start = System.currentTimeMillis();
//			RequestData.Builder builder = this.createRequestDataBuilder();
//			builder.setTransType("0501");
//			CreditQueryRequest data = CreditQueryRequest.newBuilder()
//					 							.setFamilyName("张三")
//					 							// .setIdCardno("350426198701031234")
//					 							.setIdCardno("")
//					 							.setMobile("13800138000")
//					 							.setIdType(IDType.ID_CARD.ordinal())
//					 							// 实名认证账户
//					 							// .setWalletAccountNo("0100100010005")
//					 							.setWalletAccountNo("695603264000105")
//												.build();
//			ResponseDataWrapper rdw = SDKUtil.post(url, builder, data,
//					CreditQueryResponse.class, this.serverCertificate.getPublicKey(),
//					CaGenerator.getPrivateKey(clientKeyStore, PRIVATEKEY_PASSWORD));
//			System.out.println(rdw);
//			if (null != rdw.getResponseData()) {
//				System.out.println(rdw.getResponseData());
//			}
//			System.out.println("takes " + (System.currentTimeMillis() - start));
//		}
//	
//	public void testResponse() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, Exception {
//		long start = System.currentTimeMillis();
//		RequestData.Builder builder = this.createRequestDataBuilder();
//		builder.setTransType("0201");
//		PragencyResponse data = PragencyResponse.newBuilder()
//											.setServerTransId("aaa")
//											.setClientTransId("bbb")
//											.setTransStatus("FAILURE")
//											.build();
//		ResponseDataWrapper rdw = SDKUtil.post(url, builder, data,
//				PragencyResponse.class, this.serverCertificate.getPublicKey(),
//				CaGenerator.getPrivateKey(clientKeyStore, PRIVATEKEY_PASSWORD));
//		System.out.println(rdw);
//		System.out.println("takes " + (System.currentTimeMillis() - start));
//	}
	
	protected void print(ResponseDataWrapper rdw) throws IOException {
		StringBuffer sb = new StringBuffer();
		sb.append(rdw.toString())
		  .append("\r\n");
		SpecificRecordBase responseData = rdw.getResponseData();
		if (null != responseData) {
			sb.append(responseData)
			  .append("\r\n");
		}
		System.out.println(sb.toString());
	}
	
	protected void printToDraft(ResponseDataWrapper rdw) throws IOException {
		Map<String,Object> map = new TreeMap<String,Object>();
		map.put("appId", rdw.getAppId());
		map.put("signType", rdw.getSignType());
		map.put("serverTransId", rdw.getServerTransId());
		map.put("clientTransId", rdw.getClientTransId());
		map.put("serverTransTimestamp", rdw.getServerTransTimestamp());
		map.put("data", rdw.getData());
		map.put("respCode", rdw.getRespCode());
		map.put("respMsg", rdw.getRespMsg());
		map.put("sign", rdw.getSign());
		String JsonMap = JSON.toJSONString(map);		
		StringBuffer sb = new StringBuffer();
		sb.append(JsonMap)
		  .append("\r\n");
		SpecificRecordBase responseData = rdw.getResponseData();
		if (null != responseData) {
			sb.append(responseData)
			  .append("\r\n");
		}
		System.out.println(sb.toString());
	}
	
	protected String json(ResponseDataWrapper rdw) throws IOException {
		Map<String,Object> map = new TreeMap<String,Object>();
		map.put("appId", rdw.getAppId());
		map.put("signType", rdw.getSignType());
		map.put("serverTransId", rdw.getServerTransId());
		map.put("clientTransId", rdw.getClientTransId());
		map.put("serverTransTimestamp", rdw.getServerTransTimestamp());
		map.put("data", rdw.getData());
		map.put("respCode", rdw.getRespCode());
		map.put("respMsg", rdw.getRespMsg());
		map.put("sign", rdw.getSign());
		String JsonMap = JSON.toJSONString(map);		
		StringBuffer sb = new StringBuffer();
		sb.append(JsonMap)
		  .append("\r\n");
		SpecificRecordBase responseData = rdw.getResponseData();
		if (null != responseData) {
			sb.append(responseData)
			  .append("\r\n");
		}
		return JsonMap;
	}
}
